from django.db import models

class Category(models.Model):
    name = models.CharField(max_length=100, verbose_name='分类名称')
    description = models.TextField(blank=True, verbose_name='分类描述')
    parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, verbose_name='父分类')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'api_categories'
        verbose_name = '图书分类'
        verbose_name_plural = verbose_name
        ordering = ['name']

    def __str__(self):
        return self.name

    def get_children(self):
        """获取所有子分类"""
        return Category.objects.filter(parent=self)

    def get_all_children(self):
        """获取所有子分类（递归）"""
        children = list(self.get_children())
        for child in children:
            children.extend(child.get_all_children())
        return children

    def get_all_books(self):
        """获取该分类及其所有子分类下的图书"""
        from books.models import Book
        # 获取该分类及其所有子分类的ID
        category_ids = [self.id]
        category_ids.extend([c.id for c in self.get_all_children()])

        # 查询这些分类下的所有图书
        return Book.objects.filter(category_id__in=category_ids)
